<template>
	<div>
		<div>
			<div class="search_row">
				<div>
					<el-input class="input_top" @change="dataValue" v-model="date" style="width: 220px;height: 35px;"
						placeholder="请输入创建人名称">
						<template #prefix>
							<el-icon>
								<Search />
							</el-icon>
						</template>
					</el-input>
					<el-button @click="searchs()" type="primary" style="width: 55px;height: 35px;margin-left: 10px;">
						<el-icon>
							<Search />
						</el-icon>
						查询</el-button>
					<el-button type="warning" class="button" style="width: 55px;height: 35px;margin-left: 10px"
						@click="resets()">
						<el-icon>
							<RefreshRight />
						</el-icon>
						重置
					</el-button>

				</div>
				<el-button type="primary" @click="add" style="width: 55px;height: 35px;">新增</el-button>
			</div>
			<div style="padding-bottom: 10px;">
				<el-button @click="deleList" style="height: 35px;" type="danger">批量删除</el-button>
			</div>
			<el-table @selection-change="handleSelectionChange" ref="multipleTableRef"
				v-el-table-infinite-scroll="handleTableScroll"
				:data="scenic_list.slice((currentPage - 1) * pageSize, currentPage * pageSize)" border
				style="width: 100%" :cell-style="{ 'text-align': 'center' }"
				:header-cell-style="{ 'text-align': 'center' }" stripe>
				<el-table-column type="selection" width="55" />
				<el-table-column prop="id" label="序号" width="90" />
				<el-table-column prop="name" label="创建人名称" />
				<el-table-column prop="id" label="创建人头像" width="140">
					<template #default="scope">
						<div>
							<el-image style="width: 70px; height: 50px"
								:src="testName + scope.row.img" :zoom-rate="1.2" :max-scale="7"
								:min-scale="0.2" :preview-src-list="[testName + scope.row.img]"
								:initial-index="4" fit="cover" preview-teleported />
						</div>
					</template>
				</el-table-column>

				<el-table-column prop="" width="120" label="状态">
					<template #default="scope">
						<div class="handle">
							<el-switch @change="funstatus(scope.row)"
								:model-value="scope.row.status == 0 ? true : scope.row.status == 1 ? false : scope.row.status"
								inline-prompt active-text="显示" inactive-text="隐藏" />
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="create_time" label="创建时间" width="160" />
				<el-table-column label="操作" width="200">
					<template #default="scope">
						<div class="handle">
							<el-button type="primary" @click="edit(scope.row)"
								style="width: 55px;height: 35px;">编辑</el-button>
							<el-button type="danger" style="width: 55px;height: 35px;"
								@click="deletes(scope.row)">删除</el-button>
						</div>
					</template>
				</el-table-column>
			</el-table>
			<div class="paging">
				<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
					:page-sizes="[5, 10, 20, 50]" :small="small" :disabled="disabled" background
					layout="total, sizes, prev, pager, next, jumper" :total="scenic_list.length" />
			</div>
			<div></div>
		</div>
		<!-- 新增弹窗 -->
		<el-dialog v-model="dialogVisible">
			<img style="width: 100%; height: 100%" w-full :src="dialogImageUrl" alt="Preview Image" />
		</el-dialog>
		<!-- 新增弹出框 -->
		<el-dialog v-model="dialogTableVisible" z-index="4" @close="close(ruleFormRef)" :title="disableds ? '添加' : '编辑'"
			width="50vw">
			<el-form ref="ruleFormRef" style="width:100%" :model="ruleForm" status-icon :rules="rules"
				label-width="auto" class="demo-ruleForm">
				<div v-show="hidden">

					<el-form-item label="创建人名称" prop="priceNumber">
						<el-input disabled v-model="ruleForm.pricename" style="width: 100%;" min="0"
							controls-position="right" />
					</el-form-item>
					<el-form-item label="创建人头像" prop="priceNumber">

						<!-- <img width="100px" height="90px" style="border-radius: 8px;" :src="'testName'+ruleForm.img" alt=""> -->

						<el-upload list-type="picture-card" disabled :on-preview="handlePictureCardPreview">
							<el-image :src="testName + ruleForm.img" :zoom-rate="1.2" :max-scale="7"
								:min-scale="0.2" :preview-src-list="[testName + ruleForm.img]"
								:initial-index="4" fit="cover" preview-teleported />
						</el-upload>
					</el-form-item>
				</div>
				<div style="height: 20px;"></div>


				<el-form-item label="客服详情" prop="introduce">
					<!-- <el-input v-model="ruleForm.introduce" type="textarea" style="width: 430px" placeholder="请输入公告内容" /> -->
					<vue-ueditor-wrap v-model="ruleForm.introduce" :config="editorConfig"
						editor-id="editor-demo-01"></vue-ueditor-wrap>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
					<el-button @click="closes(ruleFormRef)">取消</el-button>
				</div>
			</template>
		</el-dialog>
		<!-- 删除弹窗 -->
		<el-dialog title="删除" v-model="centerDialogVisible" width="30%" center>
			<div style="font-size: 16px">确认删除当前客服信息吗?</div>
			<span slot="footer" style="display: flex; justify-content: space-between" class="dialog-footer">
				<div></div>
				<div style="height: 30px;margin-top: 20px;">
					<el-button @click="centerDialogVisible = false">取 消</el-button>
					<el-button type="primary" @click="deleteid">确 定</el-button>
				</div>
			</span>
		</el-dialog>
		<!-- 批量删除 -->
		<el-dialog title="批量删除" v-model="centerDialogVisiblet" width="30%" center>
			<div style="font-size: 16px">确认删除这批数据吗?</div>
			<span slot="footer" style="display: flex; justify-content: space-between" class="dialog-footer">
				<div></div>
				<div>
					<el-button @click="centerDialogVisiblet = false">取 消</el-button>
					<el-button type="primary" @click="deleteid_t">确 定</el-button>
				</div>
			</span>
		</el-dialog>
	</div>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue';
import { scenicUpload } from '../../api/uploading/index'
import { announArr, announArrAdd, announArrEdit, announArrStatus, announArrDele } from '../../api/servicestts/index'
import { Search, DeleteFilled, RefreshRight } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus';
import { inject } from 'vue'
const testFn = inject('testFn')
import '../../../style/all.css'//全局css
testFn()
const testName = inject('testName')

const date = ref('');
const value1 = ref('')
const hidden = ref(false)

// 弹窗
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const fileList = ref([]);
const tokens = JSON.parse(localStorage.getItem('tokens'));
// 重置事件
function searchs() {
	// date.value = ''
	currentPage.value = 1
	scenic_list.value = arrlist.value.filter(function (item) {
		// 判断是否满足搜索条件
		if (String(item.name).indexOf(String(date.value)) > -1
		) {
			return scenic_list
		}
	})
}
function handleTableScroll() {
	console.log('滚动分页')

}

function resets() {
	date.value = ''
	renders()
}
// 点击删除出现弹窗
const centerDialogVisible = ref(false);
const titleN = ref('');
const deleteids = ref('')
function deletes(item) {
	if (item.status == 0) {
		ElMessage({
			message: '无法删除显示的客服信息',
			type: 'warning',
		})
	} else {
		centerDialogVisible.value = true;
		titleN.value = item.name;
		deleteids.value = item.id
	}

}
// 确认删除
function deleteid() {
	announArrDele({
		ids: deleteids.value,
	}, {
		token: tokens.token,
		uid: tokens.id
	}).then(res => {
		console.log(res, '删除成功或失败回调');
		centerDialogVisible.value = false;
		renders()
		ElMessage({
			message: '删除成功',
			type: 'success',
		})
	})
}
// 删除批量
// 全选单选
const multipleTableRef = ref()
const SelectArr = ref([])
const All_Delete = ref([])
const handleSelectionChange = (val) => {
	All_Delete.value = []
	SelectArr.value = val
	console.log(SelectArr.value);
	SelectArr.value.forEach(item => {
		console.log(item);
		All_Delete.value.push(item.id)
	})
	console.log(All_Delete.value);
}
// 批量删除
// 批量删除
const centerDialogVisiblet = ref(false)
const st = ref([])
function deleList() {
	st.value = []
	console.log(All_Delete.value);
	st.value.push(All_Delete.value)
	if (All_Delete.value == '') {
		ElMessage({
			message: '请勾选要删除的客服信息',
			type: 'warning',
		})
	} else {
		centerDialogVisiblet.value = true
	}
}
// 确认批量删除
const deleteid_t = () => {
	announArrDele({
		ids: st.value.join(','),
	}, {
		token: tokens.token,
		uid: tokens.id
	}).then(res => {
		console.log(res, '删除成功或失败回调');
		if (res.code == 1) {
			centerDialogVisiblet.value = false;
			renders()
			ElMessage({
				message: '删除成功',
				type: 'success',
			})
		} else if (res.code == 0) {
			ElMessage({
				message: res.msg,
				type: 'warning',
			})
		}

	})
}
// 图片放大视图
const handlePictureCardPreview = (file) => {
	// console.log(file.raw.name);
	dialogImageUrl.value = file.url;
	dialogVisible.value = true;
}
// 输入框
const search = ref('')

// 列表数据
const scenic_list = ref([])
const arrlist = ref([])
renders()
function renders() {
	announArr({
		token: tokens.token,
		uid: tokens.id
	}).then(res => {
		scenic_list.value = res.data
		arrlist.value = res.data
		console.log(res);
		for (let i = 0; i < scenic_list.value.length; i++) {
			// console.log(scenic_list.value[i].imgs.split(','));

		}
	})
}
// 上下架判断
let statust = ref('');
const statused = ref('');
function funstatus(e) {

	if (e.status == '0') {
		statust.value = '1';
	} else if (e.status == '1') {
		statust.value = '0';
	}

	if (e.status == '0') {
		ElMessage({
			message: '最少显示一条',
			type: 'warning',
		});
	} else {
		announArrStatus(
			{
				id: e.id,
				status: statust.value,
			},
			{
				token: tokens.token,
				uid: tokens.id,
			}
		).then((res) => {

			if (res.code == 1) {
				ElMessage({
					message: '操作成功',
					type: 'success',
				});
				renders();
			} else if (res.code == 0) {
				ElMessage({
					message: '最少显示一条客服信息',
					type: 'warning',
				});
			}
		});
	}

}
// input事件
const filterg = () => {
	render()
	scenic_list.value = arrlist.value.filter(function (item) {
		// 判断是否满足搜索条件
		if (String(item.name).indexOf(String(search.value)) > -1
		) {
			return scenic_list
		}
	})
}
function dataValue(value) {
	console.log(value);
	scenic_list.value = arrlist.value.filter(function (item) {
		// 判断是否满足搜索条件
		if (String(item.name).indexOf(String(value)) > -1
		) {
			return scenic_list
		}

	})


}
// 表格页码数
const pageSize = ref(5);
const currentPage = ref(1);
// 新增编辑title动态
const disableds = ref(true);
// 点击新增或确认做判断
const statusAdd = ref('');
// 点击新增
function add() {
	statusAdd.value = '1'
	dialogTableVisible.value = true
	disableds.value = true
}
const dialogTableVisible = ref(false);
// 新增输入框响应值
const ruleForm = reactive({
	idtitle: '',
	name: '',
	introduce: '',
	img: '',
	pricename: '',
	valid_time: '',
	id: ''
});
// 编辑所用id
const editDataid = ref('')
// 点击编辑
function edit(item) {
	console.log(item);
	statusAdd.value = '2'
	editDataid.value = item.id
	ruleForm.introduce = item.content;
	ruleForm.id = item.id
	ruleForm.img = item.img
	ruleForm.pricename = item.name
	dialogTableVisible.value = true;
	disableds.value = false;
	hidden.value = true
	fileList.value = [{
		url: testName + item.img
	}]
}
// 富文本
const editorConfig = reactive({
	// 编辑器不自动被内容撑高
	autoHeightEnabled: false,
	// 初始容器高度
	initialFrameHeight: 200,
	// 初始容器宽度
	initialFrameWidth: '100vw',
	UEDITOR_HOME_URL: '/UEditor/', // 访问 UEditor 静态资源的根路径，可参考常见问题1
	serverUrl: '/web/uploads', // 服务端接⼝
	uploadUrl: '/UEditor',


	// enableAutoSave: true, // 开启从草稿箱恢复功能需要⼿动设置固定的 editorId，否则组件会默认随机⼀个，如果页⾯刷新，下次渲染的时候 editorId 会重新随机，// 服务端接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
});
// 关闭新增
const close = (formEl) => {
	if (!formEl) return;
	formEl.resetFields();
	ruleForm.name = '';
	ruleForm.introduce = '';
	fileList.value = '';
	hidden.value = false
};
// 关闭新增
const closes = (formEl) => {
	if (!formEl) return;
	formEl.resetFields();
	dialogTableVisible.value = false;
};
// 表单效验集合
const ruleFormRef = ref<FormInstance>();
const validatePass = (rule: any, value: any, callback: any) => {
	if (value === '') {
		callback(new Error('Please input the password'));
	} else {
		if (ruleForm.checkPass !== '') {
			if (!ruleFormRef.value) return;
			ruleFormRef.value.validateField('checkPass', () => null);
		}
		callback();
	}
};
// 新增输入框判断效验
const rules = reactive({
	introduce: [{ required: true, message: '请输入公告内容', trigger: 'blur' }],
	// priceNumber: [{ required: true, message: '请输入', trigger: 'change' }],
	valid_time: [{ required: true, message: '请输入有效时长', trigger: 'change' }],
	img: [{ required: true, message: '请选择图片', trigger: 'blur' }],

});
// 点击新增确认
const submitForm = (formEl: FormInstance | undefined) => {

	if (!formEl) return;
	formEl.validate((valid) => {
		if (valid) {
			// 效验通过执行
			if (statusAdd.value == '1') {
				console.log(ruleForm);

				announArrAdd({
					content: ruleForm.introduce,
					create_uid: tokens.id
				}, {
					token: tokens.token,
					uid: tokens.id
				}).then(res => {
					console.log(res);
					dialogTableVisible.value = false;
					renders()
					ElMessage({
						message: '新增成功',
						type: 'success',
					})
				})

			} else if (statusAdd.value == '2') {
				announArrEdit({
					id: editDataid.value,
					content: ruleForm.introduce,

				}, {
					token: tokens.token,
					uid: tokens.id
				}).then(res => {
					console.log(res);
					if (res.code == 1) {
						dialogTableVisible.value = false;
						renders()
						ElMessage({
							message: '编辑成功',
							type: 'success',
						})
					} else {
						ElMessage({
							message: '编辑失败,与原数据一致',
							type: 'warning',
						})
					}

				})

			}

			// tableData.push(obj)
		} else {
			ElMessage.error('新增失败')
			console.log('error submit!');
			return false;
		}
	});
}


</script>

<style scoped>
.paging {
	display: flex;
	justify-content: center;
	margin-top: 10px;
}

/* 搜索一行div弹性 */
.search_row {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding-bottom: 10px;
}
</style>